<script setup lang="ts">
import { NForm, FormRules } from "naive-ui";
import { request } from "../apis";
import { notEmpty } from "../utils";
import { useRouter } from "vue-router";
//
const router = useRouter();
// 使用 NForm 组件对模板引用进行类型标注
const formRef = ref<InstanceType<typeof NForm>>();
// 表单数据
const formValues: {
  avatar: string | File;
  username: string;
  password: string;
  confirmPassword: string;
  nickname: string;
} = reactive({
  avatar: "",
  username: "",
  password: "",
  confirmPassword: "",
  nickname: "",
});
const errors = reactive({
  username: "",
  password: "",
  confirmPassword: "",
  nickname: "",
});
//
const rules: FormRules = {
  username: [
    { required: true, trigger: "blur" },
    {
      min: 3,
      max: 16,
      // message: "长度在 3 到 16 个字符",
      trigger: "blur",
    },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    {
      min: 6,
      max: 20,
      message: "长度在 6 到 20 个字符",
      trigger: "blur",
    },
  ],
  confirmPassword: [
    { required: true, message: "请确认密码", trigger: "blur" },
    {
      min: 6,
      max: 20,
      message: "长度在 6 到 20 个字符",
      trigger: "blur",
    },
    {
      validator: (_, value) => {
        return value == formValues.password;
      },
      message: "两次输入密码不一致!",
      trigger: "blur",
    },
  ],
  nickname: [
    { required: true, message: "请输入昵称", trigger: "blur" },
    { max: 50, message: "长度不能超过 50 个字符", trigger: "blur" },
  ],
};
// 用户注册
const register = async () => {
  // 表单验证
  await formRef.value?.validate();
  // 由于要实现文件上传，必须使用 FormData 对上传数据进行编码。
  const formData = new FormData();
  // 将 formValues 转换为 formData
  Object.entries(formValues).forEach(([k, v]) => {
    if (k == "avatar" && v instanceof File) {
      formData.append(k, v, v.name);
    } else formData.append(k, v);
  });
  // 发起请求
  const { data } = await request("/register", {
    method: "post",
    headers: {
      "Content-Type": "multipart/form-data",
    },
    data: formData,
  });
  if (data.success) {
    // 跳转至登录
    router.push({ name: "login" });
  } else {
    // 如果注册失败
    if (notEmpty(data.errors)) {
      Object.keys(errors).forEach((key) => {
        errors[key as keyof typeof errors] = data.errors![key].join(", ") ?? "";
      });
    }
  }
};
</script>
<template>
  <div
    class="w-full h-full relative from-teal-500 to-cyan-300 bg-gradient-to-br flex justify-center items-center"
  >
    <div
      class="w-1/2 bg-white z-10 flex justify-center p-4 rounded-md shadow-md"
    >
      <NForm
        ref="formRef"
        :model="formValues"
        :rules="rules"
        label-placement="left"
        label-width="6rem"
        :style="{
          maxWidth: '20rem',
        }"
      >
       <div style="text-align: center;">
        <h1 >创建帐户</h1>
       </div>
      
        <div class="flex justify-center">
          <ImageInput v-model="formValues.avatar" />
        </div>
        <NFormItem path="username" :feedback="errors.username">
          <NInput v-model:value="formValues.username" placeholder="Your Name" />
        </NFormItem>
        <NFormItem path="password" :feedback="errors.password">
          <NInput
            type="password"
            v-model:value="formValues.password"
            placeholder="password"
          />
        </NFormItem>
        <NFormItem path="confirmPassword" :feedback="errors.confirmPassword">
          <NInput
            type="password"
            v-model:value="formValues.confirmPassword"
            placeholder="repeat your password"
          />
        </NFormItem>
        <NFormItem path="nickname" :feedback="errors.nickname">
          <NInput v-model:value="formValues.nickname" placeholder="nickname" />
        </NFormItem>
        <div>
          <NButton
            class="w-full"
            size="large"
            type="primary"
            @click.prevent="register"
          >
            注册
          </NButton>
        </div>
        <p class="my-8">
         已有帐户？
          <a
            class="cursor-pointer text-teal-500 hover:text-teal-300 underline"
            @click="router.push({ name: 'login' })"
          >
           在此登录
          </a>
        </p>
      </NForm>
    </div>
    <svg
      class="fill-cyan-300 absolute bottom-0 col-start-1 row-start-1 h-auto w-full"
      width="1600"
      height="595"
      viewBox="0 0 1600 595"
      fill="none"
      xmlns="http://www.w3.org/2000/svg"
    >
      <path
        d="M0 338L53.3 349.2C106.7 360.3 213.3 382.7 320 393.8C426.7 405 533.3 405 640 359.3C746.7 313.7 853.3 222.3 960 189.2C1066.7 156 1173.3 181 1280 159.2C1386.7 137.3 1493.3 68.7 1546.7 34.3L1600 0V595H1546.7C1493.3 595 1386.7 595 1280 595C1173.3 595 1066.7 595 960 595C853.3 595 746.7 595 640 595C533.3 595 426.7 595 320 595C213.3 595 106.7 595 53.3 595H0V338Z"
      ></path>
    </svg>
  </div>
</template>
